package com.atguigu.tingshu.album.api;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.common.result.Result;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.commons.util.IdUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Tag(name = "上传管理接口")
@RestController
@RequestMapping("api/album")
public class FileUploadApiController {

    @Resource
    private MinioConstantProperties minioConstantProperties;

    @PostMapping("fileUpload")
    @Operation(summary = "上传文件")
    public Result<String> fileUpload(MultipartFile file) {
        try {
            //1、初始化minio客户端
            MinioClient minioClient = MinioClient.builder().endpoint(minioConstantProperties.getEndpointUrl())
                    .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecretKey())
                    .build();
            //2、判断桶是否存在，若不存在，则创建桶
            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build())) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            }
            //3、上传文件
            String filename = UUID.randomUUID().toString().replaceAll("-", "") + "." + FilenameUtils.getExtension(file.getOriginalFilename());
            minioClient.putObject(PutObjectArgs.builder()
                    //上传至minio的桶名字
                    .bucket(minioConstantProperties.getBucketName())
                    //上传至minio的文件名
                    .object(filename)
                    //上传至minio的文件流
                    .stream(file.getInputStream(), file.getSize(), -1)
                    //上传文件类型
                    .contentType(file.getContentType())
                    .build());
            //4、返回文件url
            String url = minioConstantProperties.getEndpointUrl() + "/" + minioConstantProperties.getBucketName() + "/" + filename;
            return Result.ok(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail();
    }
}
